import axios from 'axios'
import qs from 'qs'
import { baseUrl } from './env'
import { Toast } from 'vant'
import router from '../router'
// 全局设置
axios.defaults.baseURL = baseUrl
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.timeout = 15000
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  const sessionId = sessionStorage.getItem('session_id')
  if (sessionId) {
    config.headers['session_id'] = sessionId
  }
  config.data = qs.stringify(config.data)
  return config
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  Toast.clear()
  if (response.data.success === 'false') {
    if (response.data.errorCode === 'session_expired') {
      localStorage.clear()
      sessionStorage.clear()
      router.push('/login')
    }
    Toast(response.data.errorMsg)
  }
  return response
}, function (error) {
  // 对响应错误做点什么
  Toast.clear()
  Toast('请求异常，请重试')
  return Promise.reject(error)
})

const fetch = function (url, data = {}) {
  return new Promise(function (resolve, reject) {
    axios.post(url, data).then(response => {
      resolve(response.data)
    }).catch(error => {
      reject(error)
    })
  })
}

export default fetch
